package org.jetnuke.modules.news;

import org.apache.log4j.Logger;

import java.io.Writer;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.velocity.VelocityContext;
import org.jetnuke.common.ActionForward;
import org.jetnuke.common.IAction;
import org.jetnuke.common.IAdminInfo;
import org.jetnuke.common.IModuleInfo;
import org.jetnuke.common.IUserInfo;
import org.jetnuke.dao.DataAccessDriver;
import org.jetnuke.entities.MainConfig;
import org.jetnuke.entities.Stories;
import org.jetnuke.util.JetUtil;

import com.sun.syndication.feed.synd.SyndContent;
import com.sun.syndication.feed.synd.SyndContentImpl;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndEntryImpl;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.feed.synd.SyndFeedImpl;
import com.sun.syndication.io.SyndFeedOutput;

public class RSS implements IAction {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(RSS.class);

	String rssVersion = "0_91";

	public void setRssVersion(String rssVersion) {
		this.rssVersion = rssVersion;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.jetnuke.common.IAction#exec(javax.servlet.http.HttpServletRequest,
	 *      javax.servlet.http.HttpServletResponse,
	 *      org.apache.velocity.VelocityContext, org.jetnuke.common.IModuleInfo,
	 *      java.lang.String, org.jetnuke.common.IUserInfo,
	 *      org.jetnuke.common.IAdminInfo)
	 */
	public ActionForward exec(HttpServletRequest request,
			HttpServletResponse response, VelocityContext vc, IModuleInfo info,
			String op, IUserInfo ui, IAdminInfo ai) throws Exception {
		if (logger.isDebugEnabled()) {
			logger
					.debug("exec(HttpServletRequest, HttpServletResponse, VelocityContext, IModuleInfo, String, IUserInfo, IAdminInfo) - start"); //$NON-NLS-1$
		}

		MainConfig cfg = (MainConfig) request.getAttribute("MAIN_CONFIG");
		String ch_title = cfg.getSITENAME();
		String ch_url = cfg.getNUKEURL();

		SyndFeed feed = new SyndFeedImpl();
		feed.setTitle(ch_title);
		feed.setDescription(cfg.getSITENAME());
		feed.setLink(ch_url);

		// create dummy channel
		// ChannelIF channel = new Channel(ch_title);
		// channel.setDescription(cfg.getSITENAME());
		// channel.setSite(new URL(ch_url));

		Iterator it = DataAccessDriver.getInst().newStoriesDAO()
				.selectOrderBySidDescLimit(10).iterator();// storiesPeer.doSelect(new
															// Criteria().addDescendingOrderByColumn(storiesPeer.SID).setLimit(10)).iterator();
		if (ch_url.endsWith("/"))
			ch_url = ch_url.substring(0, ch_url.length() - 1);
		List entries = new ArrayList();
		GregorianCalendar gc = new GregorianCalendar();
		gc.set(Calendar.HOUR_OF_DAY, 0);
		gc.set(Calendar.MINUTE, 0);
		gc.set(Calendar.SECOND, 0);
		gc.set(Calendar.MILLISECOND, 0);
		Date dt = gc.getTime();
		while (it.hasNext()) {
			Stories st = (Stories) it.next();
			String url = ch_url;

			SyndEntry entry = new SyndEntryImpl();
			entry.setTitle(st.getTITLE());
			entry.setLink(url + "/do/news/story?id=" + st.getSID());
			entry.setPublishedDate(dt);
			SyndContent description = new SyndContentImpl();
			description.setType("text/html");
			description.setValue(st.getTITLE());
			entry.setDescription(description);
			entries.add(entry);

		}
		feed.setEntries(entries);

		// ChannelExporterIF exporter = null;
		if (rssVersion.equals("1_0"))
			feed.setFeedType("rss_1.0");
		// exporter=new
		// RSS_1_0_Exporter(response.getWriter(),request.getCharacterEncoding());
		else if (rssVersion.equals("2_0"))
			feed.setFeedType("rss_2.0");
		// exporter=new
		// RSS_2_0_Exporter(response.getWriter(),request.getCharacterEncoding());
		else if (rssVersion.equals("a0_3"))
			feed.setFeedType("atom_0.3");
		else if (rssVersion.equals("a1_0"))
			feed.setFeedType("atom_1.0");
		else
			feed.setFeedType("rss_0.91N");
		feed.setLanguage("en_US");
		// exporter=new
		// RSS_0_91_Exporter(response.getWriter(),request.getCharacterEncoding());
		// exporter.write(channel);

		SyndFeedOutput output = new SyndFeedOutput();
		JetUtil.manageReponseCookies(vc, response);
		response.setContentType("text/xml");

		Writer writer = response.getWriter();
		output.output(feed, writer);
		writer.close();

		if (logger.isDebugEnabled()) {
			logger
					.debug("exec(HttpServletRequest, HttpServletResponse, VelocityContext, IModuleInfo, String, IUserInfo, IAdminInfo) - end"); //$NON-NLS-1$
		}
		return null;
	}

}
